﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Web;
using System.Web.SessionState;
using Models;

namespace Web.Areas.Admin.Lib
{
    public class Account : admin_accountLogic
    {
        private const string Prefix = "CurrentAccount-";
        private const string Prefixkey = "eDotor-weixin";

        #region 属性
        /// <summary>
        /// 登录用户IDer
        /// </summary>
        public static int ID
        {
            get
            {
                try
                {
                    var day = DateTime.Now.ToString("yyMMdd");
                    var key_id = Common.EncryptionHelper.MD5Helper.Encryt(Prefix + "ID" + day);
                    var key_key = Common.EncryptionHelper.MD5Helper.Encryt(Prefix + "Key" + day);
                    var sessionIdValue = HttpContext.Current.Session[key_id];
                    if (sessionIdValue == null)
                    {
                        var cid = HttpContext.Current.Request.Cookies[key_id];
                        var ckey = HttpContext.Current.Request.Cookies[key_key];
                        if (cid != null && ckey != null && !string.IsNullOrWhiteSpace(cid.Value) && !string.IsNullOrWhiteSpace(ckey.Value))
                        {
                            var accountid = int.Parse(cid.Value);
                            if (ckey.Value == Common.EncryptionHelper.MD5Helper.Encryt(Prefixkey + accountid))
                            {
                                HttpContext.Current.Session[key_id] = accountid;
                                var member = new Account().Getadmin_account(accountid);
                                HttpContext.Current.Session[Prefix + "Account"] = new admin_account { username = member.username, id = accountid, name = member.name, usertype = member.usertype };
                                HttpContext.Current.Session.Timeout = 2;

                                return accountid;
                            }
                            return 0;
                        }
                        return 0;
                    }

                    int sid;
                    int.TryParse(sessionIdValue.ToString(), out sid);
                    return sid;
                }
                catch (Exception)
                {
                    return 0;
                }

            }
        }

        /// <summary>
        /// 登录用户Member对象
        /// </summary>
        public static Models.admin_account GetAccount
        {
            get
            {
                if (ID > 0)
                {
                    if (HttpContext.Current.Session[Prefix + "Account"] != null)
                    {
                        admin_account model = HttpContext.Current.Session[Prefix + "Account"] as Models.admin_account;
                        return HttpContext.Current.Session[Prefix + "Account"] as Models.admin_account;
                    }
                    else
                    {
                        var member = new Account().Getadmin_account(ID);
                        HttpContext.Current.Session[Prefix + "Account"] = new admin_account { username = member.username, id = ID, name = member.name, usertype = member.usertype };
                        return member;
                    }
                }
                else
                {
                    return null;
                }
            }
        }

        #endregion

        /// <summary>
        /// 注销
        /// </summary>
        public static void LogOut()
        {
            var now = DateTime.Now;
            var day = now.ToString("yyMMdd");
            //清除Cookie
            HttpCookie cookie = new HttpCookie(Common.EncryptionHelper.MD5Helper.Encryt(Prefix + "ID" + day));
            cookie.Expires = now.AddSeconds(-1);
            cookie.HttpOnly = true;
            HttpContext.Current.Response.AppendCookie(cookie);

            //清除Cookie
            HttpCookie cookiekey = new HttpCookie(Common.EncryptionHelper.MD5Helper.Encryt(Prefix + "Key" + day));
            cookiekey.Expires = now.AddSeconds(-1);
            cookie.HttpOnly = true;
            HttpContext.Current.Response.AppendCookie(cookiekey);

            //删除Session （取消当前会话）
            HttpContext.Current.Session.Abandon();
        }

        /// <summary>
        /// 登录
        /// </summary>
        public bool LogOn(string username, string password, bool auto)
        {
            var t = this.Getadmin_account(new Models.admin_account() { username = username, password = Common.Character.EncrytPassword(password) });
            if (t == null) return false;

            var now = DateTime.Now;
            var day = now.ToString("yyMMdd");
            HttpCookie cookie = new HttpCookie(Common.EncryptionHelper.MD5Helper.Encryt(Prefix + "ID" + day));
            cookie.Value = t.id.ToString();
            cookie.Expires = now.AddDays(1);
            cookie.HttpOnly = true;
            HttpContext.Current.Response.AppendCookie(cookie);

            HttpCookie cookiekey = new HttpCookie(Common.EncryptionHelper.MD5Helper.Encryt(Prefix + "Key" + day));
            cookiekey.Value = Common.EncryptionHelper.MD5Helper.Encryt(Prefixkey + t.id.ToString());
            cookiekey.Expires = now.AddDays(1);
            cookiekey.HttpOnly = true;
            HttpContext.Current.Response.AppendCookie(cookiekey);

            CreateNewSession();

            HttpContext.Current.Session[Common.EncryptionHelper.MD5Helper.Encryt(Prefix + "ID" + day)] = t.id;
            HttpContext.Current.Session[Prefix + "Account"] = t;
            HttpContext.Current.Session.Timeout = 30;

            return true;
        }
        public void CreateNewSession()
        {
            SessionIDManager manager = new SessionIDManager();
            manager.RemoveSessionID(HttpContext.Current);
            var newId = manager.CreateSessionID(HttpContext.Current);
            var isRedirected = true;
            var isAdded = true;
            manager.SaveSessionID(HttpContext.Current, newId, out isRedirected, out isAdded);
        }

        public void ChangeSessionID()
        {
            SessionIDManager m = new SessionIDManager();
            m.RemoveSessionID(HttpContext.Current);
            HttpApplication ctx = (HttpApplication)HttpContext.Current.ApplicationInstance;
            HttpModuleCollection mods = ctx.Modules;
            SessionStateModule sessionStateModule = (SessionStateModule)mods.Get("Session");
            MethodInfo createSessionId = sessionStateModule.GetType().GetMethod("CreateSessionId", BindingFlags.Instance | BindingFlags.NonPublic);
            MethodInfo initStateStoreItem = sessionStateModule.GetType().GetMethod("InitStateStoreItem", BindingFlags.Instance | BindingFlags.NonPublic);
            createSessionId.Invoke(sessionStateModule, null);
            SessionStateUtility.RemoveHttpSessionStateFromContext(HttpContext.Current);
            initStateStoreItem.Invoke(sessionStateModule, new object[] { true });

            FieldInfo sessioninfo = this.GetType().BaseType.BaseType.GetField("_session", BindingFlags.NonPublic | BindingFlags.Instance);
            sessioninfo.SetValue(this, HttpContext.Current.Session);
        }
    }
}